package jdbc;

import utils.JDBCUtilsOld;

import java.sql.*;
import java.util.Scanner;

/**
 * Date:2022/2/28
 * Author:ybc
 * Description:
 */
public class LoginTest {

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/wh0106?characterEncoding=utf8",
                    "root",
                    "123456");
            String sql = "select * from t_user where username = ? and password = ?";
            ps = connection.prepareStatement(sql);
            ps.setObject(1, username);
            ps.setObject(2, password);
            rs = ps.executeQuery();
            System.out.println(rs.next()?"登录成功":"登录失败");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtilsOld.close(rs, ps, connection);
        }
    }

    public static void testLoginByStatement(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/wh0106?characterEncoding=utf8",
                    "root",
                    "123456");
            statement = connection.createStatement();
            String sql = "select * from t_user where username = 'abc' or '1'='1' and password = 'abc' or '1'='1'";
            rs = statement.executeQuery(sql);
            System.out.println(rs.next()?"登录成功":"登录失败");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtilsOld.close(rs, statement, connection);
        }
    }

}
